#include "main.h"
#include "esp_spiffs.h"

#define FILE_NAME "/spiffs/hello.txt"

static const char *TAG = "config";


void configWrite()
{
    ESP_LOGI(TAG, "Opening file");
    FILE* f = fopen(FILE_NAME, "w");
    if (f == NULL) {
        ESP_LOGE(TAG, "Failed to open file for writing");
        return;
    }
    fprintf(f, "Hello World!");
    fclose(f);
    ESP_LOGI(TAG, "File written");
}


void configRead()
{
    char* data;
	FILE* fp = fopen(FILE_NAME, "r");
	fseek(fp, 0, SEEK_END);
	int size = (int)ftell(fp);
	data = (char*)malloc(size * sizeof(char));
	memset(data, 0, size);
	fseek(fp, 0, SEEK_SET);
	fread(data, size, size, fp);
	fclose(fp);
    ESP_LOGI(TAG, "configRead %s", data);
}

void initConfig() 
{
    esp_vfs_spiffs_conf_t conf = {
      .base_path = "/phy",
      .partition_label = "phy",
      .max_files = 5,
      .format_if_mount_failed = false
    };
    
    // Use settings defined above to initialize and mount SPIFFS filesystem.
    // Note: esp_vfs_spiffs_register is an all-in-one convenience function.
    esp_err_t ret = esp_vfs_spiffs_register(&conf);

    if (ret != ESP_OK) {
        if (ret == ESP_FAIL) {
            ESP_LOGE(TAG, "Failed to mount or format filesystem");
        } else if (ret == ESP_ERR_NOT_FOUND) {
            ESP_LOGE(TAG, "Failed to find SPIFFS partition");
        } else {
            ESP_LOGE(TAG, "Failed to initialize SPIFFS (%s)", esp_err_to_name(ret));
        }
        return;
    }

    configWrite();


    configRead();
}
